<html>
<head>
<script>

// Part of this code is taken from Google Mail Checker extension
var animationFrames = 36;
var animationSpeed = 10; // ms
var canvas;
var canvasContext;
var loggedInImage;
var pollIntervalMin = 1000 * 60;  // 1 minute
var pollIntervalMax = 1000 * 60 * 60;  // 1 hour
var requestFailureCount = 0;  // used for exponential backoff
var requestTimeout = 1000 * 2;  // 5 seconds
var rotation = 0;
var unreadCount = -1;
var loadingAnimation = new LoadingAnimation();


function getFeedUrl() {
  return "http://www.tfl.gov.uk/tfl/syndication/feeds/disruptions-tube-offset-now-google-widget.xml";  
}


// A "loading" animation displayed while we wait for the first response from
// Gmail. This animates the badge text with a dot that cycles from left to
// right.
function LoadingAnimation() {
  this.timerId_ = 0;
  this.maxCount_ = 8;  // Total number of states in animation
  this.current_ = 0;  // Current state
  this.maxDot_ = 4;  // Max number of dots in animation
}

LoadingAnimation.prototype.paintFrame = function() {
  var text = "";
  for (var i = 0; i < this.maxDot_; i++) {
    text += (i == this.current_) ? "." : " ";
  }
  if (this.current_ >= this.maxDot_)
    text += "";

  chrome.browserAction.setBadgeText({text:text});
  this.current_++;
  if (this.current_ == this.maxCount_)
    this.current_ = 0;
}

LoadingAnimation.prototype.start = function() {
  if (this.timerId_)
    return;

  var self = this;
  this.timerId_ = window.setInterval(function() {
    self.paintFrame();
  }, 100);
}

LoadingAnimation.prototype.stop = function() {
  if (!this.timerId_)
    return;

  window.clearInterval(this.timerId_);
  this.timerId_ = 0;
}


chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
    getInboxCount(function(count) {
      updateUnreadCount(count);
    });
});


function init() {
  canvas = document.getElementById('canvas');
  loggedInImage = document.getElementById('logged_in');
  canvasContext = canvas.getContext('2d');

  chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255]});
  loadingAnimation.start();
  startRequest();
}

function scheduleRequest() {
  var randomness = Math.random() * 2;
  var exponent = Math.pow(2, requestFailureCount);
  var delay = Math.min(randomness * pollIntervalMin * exponent,
                       pollIntervalMax);
  delay = Math.round(delay);
  window.setTimeout(startRequest, delay);
}

// ajax stuff
function startRequest() {
  getInboxCount(
    function(count) {
      loadingAnimation.stop();
      updateUnreadCount(count);
      scheduleRequest();
    },
    function() {
      loadingAnimation.stop();
      showLoggedOut();
      scheduleRequest();
    }
  );
}

function getInboxCount(onSuccess, onError) {
  var xhr = new XMLHttpRequest();
  var abortTimerId = window.setTimeout(function() {
    xhr.abort();  // synchronously calls onreadystatechange
  }, requestTimeout);

  function handleSuccess(count) {
    requestFailureCount = 0;
    window.clearTimeout(abortTimerId);
    if (onSuccess)
      onSuccess(count);
  }

  function handleError() {
    ++requestFailureCount;
    window.clearTimeout(abortTimerId);
    if (onError)
      onError();
  }

  try {
    xhr.onreadystatechange = function(){
      if (xhr.readyState != 4)
        return;		 
	  var numProblems = 0;
	  var myregexp = /<div class="message">/g;
	  var match = myregexp.exec(xhr.responseText);
	  while (match != null) {
			match = myregexp.exec(xhr.responseText);
			numProblems++;
		}	 	  	
	
	  numProblems +='';
	  //alert("numProblems:" + numProblems);
      handleSuccess(numProblems);
    }

    xhr.onerror = function(error) {
      handleError();
    }

    xhr.open("GET", getFeedUrl(), true);
    xhr.send(null);
  } catch(e) {
    console.error("exception: " + e);
    handleError();
  }
}


function updateUnreadCount(count) {
  if (unreadCount != count) {
    unreadCount = count;
    animateFlip();
  }
}


function ease(x) {
  return (1-Math.sin(Math.PI/2+x*Math.PI))/2;
}

function animateFlip() {
  rotation += 1/animationFrames;
  drawIconAtRotation();

  if (rotation <= 1) {
    setTimeout("animateFlip()", animationSpeed);
  } else {
    rotation = 0;
    drawIconAtRotation();
    chrome.browserAction.setBadgeText({
      text: unreadCount != "0" ? unreadCount : ""
    });
    chrome.browserAction.setBadgeBackgroundColor({color:[208, 0, 24, 255]});
  }
}

function showLoggedOut() {
  unreadCount = -1;
  chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
  chrome.browserAction.setBadgeText({text:"?"});
}

function drawIconAtRotation() {
  canvasContext.save();
  canvasContext.clearRect(0, 0, canvas.width, canvas.height);
  canvasContext.translate(
      Math.ceil(canvas.width/2),
      Math.ceil(canvas.height/2));
  canvasContext.rotate(2*Math.PI*ease(rotation));
  canvasContext.drawImage(loggedInImage,
      -Math.ceil(canvas.width/2),
      -Math.ceil(canvas.height/2));
  canvasContext.restore();

  chrome.browserAction.setIcon({imageData:canvasContext.getImageData(0, 0,
      canvas.width,canvas.height)});
}


</script>
</head>
<body onload="init()">
<img id="logged_in" src="on.png">
<canvas id="canvas" width="19" height="19">
</body>
</html>

